// pages/index/index.js
var app = getApp();
var getSign = require('../../utils/getSign/util.js')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    baseUrl: '',
    currentSwiper: 0,
    articleData:[],
    bannerData:[],
    phone:'',
    productData:[],
    wx:'',
    isAuthorizationShow: false,
    xieyi: []
  },
  //外部网页
  gooutweb: function (event){
    var url = event.currentTarget.dataset['url'].replace('?', '$')
    url = url.replace(/=/g, '%')
    url = url.replace(/&/g, '@')
    wx.navigateTo({
      url: '/pages/outweb/outweb?url='+url,
    })
  },
  //拨打电话
  bodadianhua: function () {
    wx.makePhoneCall({
      phoneNumber: this.data.phone
    })
  },
  //添加微信
  tianjiaweixin: function(){
    wx.setClipboardData({
      data: this.data.wx,
      success: function (res) {
        wx.getClipboardData({
          success: function (res) {
            console.log('复制成功')
            console.log(res.data) // data
            wx.showToast({
              title: '微信号已复制',
              icon: 'success',
              duration: 2000
            })
            setTimeout(()=>{
              wx.showToast({
                title: '请添加好友',
                icon: 'success',
                duration: 2000
              })
            },2000)
          }
        })
      }
    })
  },
  goTodutys: function (event) {
    var url = event.currentTarget.dataset['url'].replace('?', '$')
    url = url.replace(/=/g, '%')
    url = url.replace(/&/g, '@')
    wx.navigateTo({
      url: '/pages/outweb/outweb?url=' + url,
    })
  },
  goToabout:function(){
    wx.navigateTo({
      url: '/pages/about/about',
    })
  },
  goToShopDetail: function (event){
    var id = event.currentTarget.dataset['id']
    wx.navigateTo({
      url: '/pages/shopDetail/shopDetail?id='+id,
    })
  },
  //跳转到个人购买流程
  goToPrivateWay: function (event) {
    var url = event.currentTarget.dataset['url'].replace('?', '$')
    url = url.replace(/=/g, '%')
    url = url.replace(/&/g, '@')
    console.log(url)
    wx.navigateTo({
      url: '/pages/outweb/outweb?url='+url
    })
  },
  //跳转到企业购买流程
  goToEnterpriseWay: function (event){
    var url = event.currentTarget.dataset['url'].replace('?', '$')
    url = url.replace(/=/g, '%')
    url = url.replace(/&/g, '@')
    wx.navigateTo({
      url: '/pages/outweb/outweb?url='+url
    })
  },
  goToSuccesssCases: function(){
    wx.navigateTo({
      url: '/pages/successCase/successCase'
    })
  },

  swiperChange: function (e) {
    this.setData({
      currentSwiper: e.detail.current
    })
  },
  //授权获取用户信息
  onGotUserInfo: function (e) {
    if (e.detail.errMsg === "getUserInfo:ok") {
      app.userInfo = e.detail.userInfo
      console.log(app.userInfo, "app")
      wx.setStorage({
        key: 'userInfo',
        data: e.detail.userInfo
      })
      //授权成功
      this.setData({
        isAuthorizationShow: false
      })
      //登录
      wx.login({
        success(res) {
          if (res.code) {
            var url = 'https://wx-app-api.sjune.cn/yuren/API.ashx'
            var method = 'POST'
            var data = {
              'js_code': res.code,
              'Api_Type': '001',
            }
            var message = ''
            getSign.request(url, method, data, message).then(
              (res) => {
                //获取了session_key openid
                console.log(res, 'session_key openid')
                wx.setStorage({
                  key: 'openid',
                  data: JSON.parse(res.Data)
                })
                var name = app.userInfo.nickName;
                var nick = name.replace(/\uD83C[\uDF00-\uDFFF]|\uD83D[\uDC00-\uDE4F]/g, "口");
                var userinfos = {
                  'Api_Type': '002',
                  'openId': JSON.parse(res.Data).openid,
                  'avatarUrl': app.userInfo.avatarUrl,
                  'nickName': nick,
                  'sex': app.userInfo.gender,
                  'country': app.userInfo.country,
                  'province': app.userInfo.province,
                  'city': app.userInfo.city
                }
                //获取用户登录态
                getSign.request('https://wx-app-api.sjune.cn/yuren/API.ashx', 'POST', userinfos, '').then(
                  (res) => {
                    console.log(res, '登录态')
                    wx.showTabBar({})
                    //存储memberInfo
                    wx.setStorage({
                      key: 'memberInfo',
                      data: res.Data
                    })
                    //跳转到首页
                    // wx.switchTab({
                    //   url: '/pages/index/index',
                    // })
                  },
                  (err) => {
                    console.log(err, '登录态失败')
                  }
                )
              },
              (err) => {
                console.log(err, '获取失败')
              }
            )
          } else {
            console.log('登录失败！' + res.errMsg)
          }
        }
      })

    } else {
      //未授权
      wx.showToast({
        title: '请授权',
        icon: 'loading',
        duration: 1000
      })
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      baseUrl: app.baseUrl
    })
    //检查Session_key是否过期
    wx.checkSession({
      success: (res) => {
        //未过期
        console.log('session_key 未过期')
        var memberInfo = wx.getStorageSync('memberInfo')
        if (memberInfo.MemberToken) {
              
            
        } else {
          //过期
          wx.hideTabBar({
            success: () => {
              this.setData({
                isAuthorizationShow: true
              })
            }
          })
        }

      },
      fail: (res) => {
        //过期
        wx.hideTabBar({
          success:()=>{
            this.setData({
              isAuthorizationShow: true
            })
          }
        })
        
      }

    })


    //是否有数据
    //没有数据 请求
    var member = {
      'Api_Type': '003',
      // 'Member_Id': memberInfo.MemberId,
      // 'Member_Token': memberInfo.MemberToken
    }
    //获取
    getSign.request('https://wx-app-api.sjune.cn/yuren/API.ashx', 'POST', member
      , '').then(
        (res) => {
          console.log(res, '首页信息')
          if (res.Status == 2) {
            this.setData({
              phone: '',
            })
            wx.clearStorage({
              success: () => {
                wx.hideTabBar({
                  success: () => {
                    this.setData({
                      isAuthorizationShow: true
                    })
                  }
                })
              }
            })

          } else if (res.Status == 0){
            this.setData({
              articleData: res.Data.articleData,
              bannerData: res.Data.bannerData,
              phone: res.Data.phone,
              productData: res.Data.productData,
              wx: res.Data.wx
            })
            wx.setStorage({
              key: 'phone',
              data: res.Data.phone,
            })

            wx.setStorage({
              key: 'wx',
              data: res.Data.wx,
            })
          }

        },
        (err) => {
          console.log(err, '首页信息失败')
        }
      )
      
    //发送请求
    var postArgs = {
      'Api_Type': '025',
      'page': 1
      // 'Member_Id': memberInfo.MemberId,
      // 'Member_Token': memberInfo.MemberToken
    }
    //获取
    getSign.request('https://wx-app-api.sjune.cn/yuren/API.ashx', 'POST', postArgs, '').then(
      (res) => {
        console.log(res, '登录协议')
        if (res.Status == 2) {
          wx.clearStorage({
            success: () => {
              wx.hideTabBar({
                success: () => {
                  this.setData({
                    isAuthorizationShow: true
                  })
                }
              })
            }
          })
        } else if (res.Status == 0) {
          this.setData({
            xieyi: res.Data,
          })
        }
      },
      (err) => {
        console.log(err.Message, '协议失败')
      }
    )


    
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.onLoad()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})